<template>
  <el-dialog
    append-to-body
    :title="title"
    :visible.sync="visible"
    width="1000px"
  >
    <el-form>
      <el-form-item>
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="item in list"
            :key="item.roleId"
            :label="item.roleId"
          >
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="btnLoading" @click="submitForm">
        确 定
      </el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { roleList } from "@/api/role";
import { userBindRoles } from "@/api/user";

export default {
  data() {
    return {
      list: [],
      checkList: [],
      btnLoading: false,
      loading: false,
      queryParams: {
        name: undefined,
      },
      title: "绑定角色",
      userData: {},
      visible: false,
    };
  },
  mounted() {
    this.getRoles();
  },
  methods: {
    init(row) {
      this.userData = row || {};
      if (row.roles && row.roles.length) {
        this.checkList = row.roles.map((item) => item.roleId);
      } else {
        this.checkList = [];
      }
      this.title = `${row.username}绑定角色`;
      this.visible = true;
    },
    cancel() {
      this.checkList = [];
      this.visible = false;
    },
    submitForm() {
      this.btnLoading = true;
      userBindRoles({
        uid: this.userData.uid,
        roleIds: this.checkList,
      })
        .then((res) => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "操作成功",
            });
            this.cancel();
            this.$emit("getList");
          } else {
            this.$message({
              type: "error",
              message: res.msg,
            });
          }
        })
        .finally(() => (this.btnLoading = false));
    },
    getRoles() {
      this.loading = true;

      roleList({ page: 1, size: 100 })
        .then((res) => {
          this.list = res.data.items || [];
        })
        .finally(() => (this.loading = false));
    },
  },
};
</script>

<style></style>
